package cn.chinaunicom.dingtalk.sender.service.impl;


import cn.chinaunicom.dingtalk.sender.entity.interactive.CardInstances;
import cn.chinaunicom.dingtalk.sender.entity.interactive.InteractiveCardVo;
import cn.chinaunicom.dingtalk.sender.service.IDingTalkService;
import cn.hutool.json.JSONObject;

import com.aliyun.dingtalkcard_1_0.models.CreateCardResponse;
import com.aliyun.dingtalkcard_1_0.models.UpdateCardResponse;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardHeaders;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardRequest;
import com.aliyun.dingtalkim_1_0.models.SendInteractiveCardResponse;
import com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenResponse;
import com.aliyun.tea.TeaException;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class DingTalkService implements IDingTalkService {


    @Value("${dingtalk.endpoint}")
    private String endpoint;
    @Value("${dingtalk.protocol}")
    private String protocol;
    @Value("${dingtalk.appkey}")
    private String appkey;
    @Value("${dingtalk.appseret}")
    private String appseret;

    private com.aliyun.dingtalkim_1_0.Client createClientV1() throws Exception {
        Config config = new Config();
        config.protocol = protocol;
        config.regionId = "central";
        config.endpoint = endpoint;
        return new com.aliyun.dingtalkim_1_0.Client(config);
    }

    private com.aliyun.dingtalkoauth2_1_0.Client createClientV2() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = protocol;
        config.regionId = "central";
        config.endpoint = endpoint;
        return new com.aliyun.dingtalkoauth2_1_0.Client(config);
    }


    private String getAccessToken() throws Exception {
        com.aliyun.dingtalkoauth2_1_0.Client client = createClientV2();
        com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest getAccessTokenRequest = new com.aliyun.dingtalkoauth2_1_0.models.GetAccessTokenRequest()
                .setAppKey(appkey)
                .setAppSecret(appseret);
        try {
            GetAccessTokenResponse response = client.getAccessToken(getAccessTokenRequest);
            return response.getBody().getAccessToken();
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }
        }
        return null;
    }

    @Override
    public String sendInteractiveCards(InteractiveCardVo cards) {
        JSONObject obj = new JSONObject();
        try {
            CardInstances cardInstall = new CardInstances();
            cardInstall.setCardData(new JSONObject(cards.getCardData()));
            cardInstall.setCardTemplateId(cards.getCardTemplateId());
            cardInstall.setOutTrackId(cards.getOutTrackId());
            JSONObject cardInstances = cardInstances(cardInstall);
            if (cardInstances != null) {
                com.aliyun.dingtalkim_1_0.Client client = createClientV1();
                SendInteractiveCardHeaders sendInteractiveCardHeaders = new SendInteractiveCardHeaders();
                sendInteractiveCardHeaders.xAcsDingtalkAccessToken = getAccessToken();
                SendInteractiveCardRequest.SendInteractiveCardRequestCardOptions cardOptions = new SendInteractiveCardRequest.SendInteractiveCardRequestCardOptions()
                        .setSupportForward(cards.isSupportForward());
                java.util.Map<String, String> atOpenIds = cards.getAtUsers();
                SendInteractiveCardRequest.SendInteractiveCardRequestCardData cardData = new SendInteractiveCardRequest.SendInteractiveCardRequestCardData();
                if (cards.getCardData() != null) {
                    java.util.Map<String, String> cardDataCardMediaIdParamMap = cards.getCardData().getCardMediaIdParamMap();
                    java.util.Map<String, String> cardDataCardParamMap = cards.getCardData().getCardParamMap();
                    cardData.setCardParamMap(cardDataCardParamMap)
                            .setCardMediaIdParamMap(cardDataCardMediaIdParamMap);
                }
                SendInteractiveCardRequest sendInteractiveCardRequest = new SendInteractiveCardRequest()
                        .setCardTemplateId(cards.getCardTemplateId())
                        .setConversationType(cards.getConversationType())
                        .setCardData(cardData)
                        .setUserIdType(cards.getUserIdType())
                        .setCardOptions(cardOptions)
                        .setPullStrategy(cards.isPullStrategy());
                sendInteractiveCardRequest.setOutTrackId(cards.getOutTrackId());
                sendInteractiveCardRequest.setCallbackRouteKey(cards.getCallbackRouteKey());
                if (StringUtils.isNotEmpty(cards.getOpenConversationId())) {
                    sendInteractiveCardRequest.setOpenConversationId(cards.getOpenConversationId());
                }
                if (!cards.getReceiverUserIdList().isEmpty()) {
                    sendInteractiveCardRequest.setReceiverUserIdList(cards.getReceiverUserIdList());
                }

                if (StringUtils.isNotEmpty(cards.getRobotCode())) {
                    sendInteractiveCardRequest.setRobotCode(cards.getRobotCode());
                }

                if (StringUtils.isNotEmpty(cards.getChatBotId())) {
                    sendInteractiveCardRequest.setChatBotId(cards.getChatBotId());
                }
                if (!atOpenIds.isEmpty()) {
                    sendInteractiveCardRequest.setAtOpenIds(atOpenIds);
                }
                SendInteractiveCardResponse response = client.sendInteractiveCardWithOptions(sendInteractiveCardRequest, sendInteractiveCardHeaders, new RuntimeOptions());
                obj = new JSONObject(response.getBody());
            } else {
                obj.putOpt("success", false);
                obj.putOpt("msg", "实例化卡片失败");
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
            obj.putOpt("success", false);
            obj.putOpt("msg", e.getMessage());
        }
        return obj.toString();
    }

    @Override
    public void updateInteractiveCards(InteractiveCardVo cards) throws Exception {
        com.aliyun.dingtalkcard_1_0.Client client = createCardClient();
        com.aliyun.dingtalkcard_1_0.models.UpdateCardHeaders updateCardHeaders = new com.aliyun.dingtalkcard_1_0.models.UpdateCardHeaders();
        updateCardHeaders.xAcsDingtalkAccessToken = getAccessToken();
        com.aliyun.dingtalkcard_1_0.models.UpdateCardRequest.UpdateCardRequestCardUpdateOptions cardUpdateOptions = new com.aliyun.dingtalkcard_1_0.models.UpdateCardRequest.UpdateCardRequestCardUpdateOptions()
                .setUpdateCardDataByKey(true)
                .setUpdatePrivateDataByKey(false);
        java.util.Map<String, String> cardDataCardParamMap = new HashMap<>();

        if (cards.getCardData() != null) {
            cardDataCardParamMap = cards.getCardData().getCardParamMap();
        }
        com.aliyun.dingtalkcard_1_0.models.UpdateCardRequest.UpdateCardRequestCardData cardData = new com.aliyun.dingtalkcard_1_0.models.UpdateCardRequest.UpdateCardRequestCardData()
                .setCardParamMap(cardDataCardParamMap);
        com.aliyun.dingtalkcard_1_0.models.UpdateCardRequest updateCardRequest = new com.aliyun.dingtalkcard_1_0.models.UpdateCardRequest()
                .setOutTrackId(cards.getOutTrackId())
                .setCardData(cardData)
                .setPrivateData(cards.getPrivateData())
                .setCardUpdateOptions(cardUpdateOptions)
                .setUserIdType(1);
        try {
            UpdateCardResponse updateCardResponse = client.updateCardWithOptions(updateCardRequest, updateCardHeaders, new com.aliyun.teautil.models.RuntimeOptions());
            System.err.println(updateCardResponse.getBody().toString());
        } catch (TeaException err) {
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        } catch (Exception _err) {
            TeaException err = new TeaException(_err.getMessage(), _err);
            if (!com.aliyun.teautil.Common.empty(err.code) && !com.aliyun.teautil.Common.empty(err.message)) {
                // err 中含有 code 和 message 属性，可帮助开发定位问题
            }

        }
    }

    public com.aliyun.dingtalkcard_1_0.Client createCardClient() throws Exception {
        com.aliyun.teaopenapi.models.Config config = new com.aliyun.teaopenapi.models.Config();
        config.protocol = protocol;
        config.regionId = "central";
        config.endpoint = endpoint;
        return new com.aliyun.dingtalkcard_1_0.Client(config);
    }

    @Override
    public JSONObject cardInstances(CardInstances instances) {
        try {
            com.aliyun.dingtalkcard_1_0.Client client = createCardClient();
            com.aliyun.dingtalkcard_1_0.models.CreateCardHeaders createCardHeaders = new com.aliyun.dingtalkcard_1_0.models.CreateCardHeaders();
            createCardHeaders.xAcsDingtalkAccessToken = getAccessToken();
            com.aliyun.dingtalkcard_1_0.models.CreateCardRequest.CreateCardRequestCardData cardData = new com.aliyun.dingtalkcard_1_0.models.CreateCardRequest.CreateCardRequestCardData()
                    .setCardParamMap(instances.getCardData() != null ? instances.getCardData().get("cardParamMap", Map.class) : null);
            com.aliyun.dingtalkcard_1_0.models.CreateCardRequest createCardRequest = new com.aliyun.dingtalkcard_1_0.models.CreateCardRequest()
                    .setUserId(instances.getUserId())
                    .setCardTemplateId(instances.getCardTemplateId())
                    .setOutTrackId(instances.getOutTrackId())
                    .setCallbackRouteKey(instances.getCallbackRouteKey())
                    .setCallbackType(instances.getCallbackType())
                    .setCardData(cardData)
                    .setPrivateData(instances.getPrivateData())
                    .setUserIdType(instances.getUserIdType());
            RuntimeOptions options = new com.aliyun.teautil.models.RuntimeOptions();
            CreateCardResponse rsp = client.createCardWithOptions(createCardRequest, createCardHeaders, options);

            return new JSONObject(rsp.getBody());
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
        return null;
    }
}
